<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { AreaItem } from '@/apis/model/resolve'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import {
  addCdnGroupApi,
  getCdnGroupListApi,
  updateCdnGroupApi,
} from '@/apis/modules/cdn.ts'

interface IProp {
  record?: AreaItem
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits<IEmits>()
interface IEmits {
  (e: 'reload', flag: boolean): void
}
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive({
  name: '',
  type: 1,
  origin_strategy: 1,
  upstream_group_ids: [{ group: '' }],
  remark: '',
})

const rules: Record<string, FieldRule[] | FieldRule> = {
  name: [{ required: true, message: '请输入分组名称' }],
  type: [{ required: true, message: '请选择分组类型' }],
  origin_strategy: [{ required: true, message: '请选择回源策略' }],
  // resolve_domain_id: [{ required: true, message: '请选择集群域名' }],
  // cname: cnameRules,
}
const title = computed(() => (props.record?.id ? '编辑分组' : '新建分组'))

// function handleName() {
//   formState.cname = randomCname()
// }

const GroupOptions = ref<LabelValue[]>([])
async function createArea() {
  const data = { ...omit(formState, ['cname']) }
  if (formState.origin_strategy === 1) {
    data.upstream_group_ids = []
  } else {
    data.upstream_group_ids = formState.upstream_group_ids.map(
      item => item.group,
    )
  }
  await addCdnGroupApi(data).then(() => {
    Message.success('操作成功')
    visible.value = false
  })
}
async function updateArea() {
  const data = {
    ...formState,
    id: props.record!.id!,
  }

  if (formState.origin_strategy === 1) {
    data.upstream_group_ids = []
  } else {
    data.upstream_group_ids = formState.upstream_group_ids.map(
      item => item.group,
    )
  }
  await updateCdnGroupApi(data).then(() => {
    Message.success('操作成功')
    visible.value = false
  })
}
// 检验上游组是否重复
function hasDuplicates(arr) {
  return new Set(arr).size !== arr.length
}
async function handleSubmit() {
  const error = await formRef.value?.validate()

  if (error)
    return false
  if (hasDuplicates(formState.upstream_group_ids.map(item => item.group))) {
    Message.error('上游组不能重复')
    return false
  }
  return props.record?.id ? updateArea() : createArea()
}

function handleClose() {
  formRef.value?.resetFields()
  formState.name = ''
  formState.type = 1
  formState.origin_strategy = 1
  formState.upstream_group_ids = [{ group: '' }]
  formState.remark = ''
  emit('reload', !!props.record?.id)
}

async function handleOpen() {
  // try {
  //   const res = await getCdnDomainListApi({ limit: 0 })
  //   const list = res.list ?? []
  //   domainOptions.value = list
  //     .map(item => ({ label: item.name!, value: item.id! }))
  //     .filter(Boolean)
  // } catch (error) {
  //   console.error(error)
  // }
  getGroups()
  if (props.record) {
    formState.name = props.record.name!
    formState.type = props.record.type!
    formState.origin_strategy = props.record.origin_strategy!
    if (props.record.upstreams.length > 0) {
      formState.upstream_group_ids = props.record.upstreams?.map(item => ({
        group: item.id!,
      })) ?? [{ group: '' }]
    } else {
      formState.upstream_group_ids = [{ group: '' }]
    }

    // formState.cname = props.record.cname?.replace('cluster-', '') ?? ''
    // formState.resolve_domain_id = props.record.resolve_domain_id!
  }
}
// 获取上游回源可选择列表
async function getGroups() {
  const res = await getCdnGroupListApi({ limit: 0, type: 2 })
  GroupOptions.value
    = res.list
      ?.filter(item => (item.id ?? '') !== props.record?.id)
      ?.map(item => ({
        label: item.name!,
        value: item.id!,
        type: item.type || 0,
      })) ?? []
}

const OptionalList = computed(() => {
  //  return GroupOptions.value.filter(item => !formState.upstream_group_ids.find(i => i.group === item.value))
  return GroupOptions.value.filter(item => item.type === 2)
})

// onMounted(() => {
//   handleOpen()
// })
// 阿拉伯数转化成中文数字，并调整更为口语化
function numberToChineseWithUnits(num: number) {
  const chineseDigits = [
    '零',
    '一',
    '二',
    '三',
    '四',
    '五',
    '六',
    '七',
    '八',
    '九',
  ]
  const units = ['', '十', '百', '千', '万', '十', '百', '千', '亿']

  const numStr = num.toString()
  const length = numStr.length
  const result = []

  for (let i = 0; i < length; i++) {
    const digit = Number.parseInt(numStr[i])
    const position = length - i - 1
    if (digit !== 0) {
      result.push(chineseDigits[digit])
    } else {
      if (
        result.length > 0
        && result[result.length - 1] !== '零'
        && i !== length - 1
      ) {
        result.push('零')
      }
      continue
    }
    if (position > 0 && digit !== 0) {
      result.push(units[position])
    }
  }

  if (result.length >= 2 && result[0] === '一' && result[1] === '十') {
    result.shift()
  }

  return result.join('')
}

const tableColumn = buildColumns([
  {
    title: '存储目录',
    slotName: 'ip',
  },
  {
    title: '分配容量',
    slotName: 'capacity',
    width: 260,
  },
  {
    title: '操作',
    slotName: 'action',
    cellClass: 'actions-cell',
    width: 56,
  },
])

const nodeIpRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    if (!value) {
      return callback('上游分组不能为空')
    }
    callback()
  },
}

function handleTableCommand(command: string, index?: number) {
  const map: Record<string, any> = {
    add: () => {
      formState.upstream_group_ids.push({
        group: '',
      })
    },
    delete: () => {
      // formRef.value?.resetFields(`upstream_group_ids[${index}].ip`)
      formState.upstream_group_ids!.splice(index!, 1)
    },
  }
  map[command] && map[command]()
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-close="handleClose"
    :before-open="handleOpen"
    ok-text="保存"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :rules="rules"
      :model="formState"
    >
      <a-form-item
        label="分组名称"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入分组名称"
        />
      </a-form-item>
      <a-form-item
        label="分组类型"
        field="type"
        asterisk-position="end"
      >
        <a-radio-group
          v-model="formState.type"
          class="ml-2"
          :disabled="!!props.record?.id"
        >
          <a-radio :value="1">
            边缘组
          </a-radio>
          <a-radio :value="2">
            上游组
          </a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        label="回源策略"
        field="origin_strategy"
        asterisk-position="end"
      >
        <div class="w-full">
          <div class="h-8">
            <a-radio-group
              v-model="formState.origin_strategy"
              class="ml-2"
            >
              <a-radio :value="1">
                直接回源
              </a-radio>
              <a-radio :value="2">
                上游回源
              </a-radio>
            </a-radio-group>
          </div>

          <div v-if="formState.origin_strategy === 2">
            <a-table
              :columns="tableColumn"
              :data="formState.upstream_group_ids"
              class="node-ip-table"
              :pagination="false"
              :show-header="false"
              :scroll="{ y: 200 }"
            >
              <template #ip="{ rowIndex }">
                上游组{{ numberToChineseWithUnits(rowIndex + 1) }}
              </template>
              <template #capacity="{ record, rowIndex }">
                <a-form-item
                  :field="`upstream_group_ids[${rowIndex}].group`"
                  hide-asterisk
                  hide-label
                  :rules="nodeIpRules"
                  validate-trigger="blur"
                >
                  <a-select
                    v-model="record.group"
                    placeholder="请选择上游分组"
                    :options="OptionalList"
                  />
                </a-form-item>
              </template>
              <template #action="{ rowIndex }">
                <a-link
                  :hoverable="false"
                  status="danger"
                  :disabled="formState.upstream_group_ids.length <= 1"
                  @click="handleTableCommand('delete', rowIndex)"
                >
                  <i-icons-delete size="16px" />
                </a-link>
              </template>
              <template #footer>
                <a-link
                  class="cloud-diverse-select h-[30px] w-fit items-center gap-x-2 !flex"
                  :hoverable="false"
                  @click="handleTableCommand('add')"
                >
                  <i-icons-table-add />
                  添加上游组
                </a-link>
              </template>
            </a-table>
          </div>
        </div>
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
.cloud-diverse-select {
  :deep(.arco-input-prepend) {
    border-radius: 8px 0px 0px 8px;
    border-top: 1px solid var(--border-2, #e5e6eb);
    border-left: 1px solid var(--border-2, #e5e6eb);
    border-bottom: 1px solid var(--border-2, #e5e6eb);
    border-right: none;
  }
  :deep(.arco-input-wrapper) {
    width: 260px;
    //border-left: none !important;
    border-radius: 0 !important;
  }
  :deep(.arco-select-view) {
    padding-left: 4px;
    border-left: none;
    border-radius: 0px 8px 8px 0px;
  }
}

.node-ip-table {
  //border: 1px solid #dfe2e5;
  //@apply rounded-2 overflow-hidden;

  :deep(.arco-table-container) {
    border-radius: 8px 8px 0px 0px !important;
  }

  :deep(.arco-table-tr) {
    @apply !bg-#fff;
  }

  :deep(.arco-table-th) {
    @apply !bg-transparent;
  }

  :deep(.arco-table-footer) {
    //border-width: 0px !important;
    border-radius: 0px 0px 8px 8px !important;
    border: 1px solid #f0f5f5;
    border-top: none;
  }
}
</style>
